/**
 * 插件管理JavaScript
 */
class PluginManager {
    constructor() {
        this.baseUrl = '/adminapi/plugin/manager';
        this.token = this.getAdminToken();
        this.currentPage = 1;
        this.pageSize = 12;
        this.searchKeyword = '';
        this.plugins = []; // 初始化插件数组
        this.init();
    }

    /**
     * 获取管理员token
     */
    getAdminToken() {
        try {
            const admin = localStorage.getItem('admin');
            if (admin) {
                const adminData = JSON.parse(admin);
                return adminData.accessToken;
            }
        } catch (e) {
            console.error('获取token失败:', e);
        }
        return null;
    }

    /**
     * 初始化
     */
    init() {
        this.bindEvents();
        this.loadPlugins();
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 启用/禁用插件
        document.addEventListener('click', (e) => {
            const enableBtn = e.target.closest('.btn-enable');
            const disableBtn = e.target.closest('.btn-disable');
            const uninstallBtn = e.target.closest('.btn-uninstall');
            const configBtn = e.target.closest('.btn-config');
            const manageBtn = e.target.closest('.btn-manage');

            if (enableBtn) {
                e.preventDefault();
                const pluginName = enableBtn.dataset.plugin;
                this.enablePlugin(pluginName);
            } else if (disableBtn) {
                e.preventDefault();
                const pluginName = disableBtn.dataset.plugin;
                this.disablePlugin(pluginName);
            } else if (uninstallBtn) {
                e.preventDefault();
                const pluginName = uninstallBtn.dataset.plugin;
                this.uninstallPlugin(pluginName);
            } else if (configBtn) {
                e.preventDefault();
                const pluginName = configBtn.dataset.plugin;
                this.showConfig(pluginName);
            } else if (manageBtn) {
                e.preventDefault();
                const pluginName = manageBtn.dataset.plugin;
                const entryUrl = manageBtn.dataset.entry;
                this.openPluginManagement(pluginName, entryUrl);
            }
        });

        // 配置表单提交
        const configForm = document.getElementById('configForm');
        if (configForm) {
            configForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveConfig();
            });
        }

        // 市场搜索
        const marketSearchInput = document.getElementById('marketSearch');
        if (marketSearchInput) {
            marketSearchInput.addEventListener('input', (e) => {
                this.searchMarket(e.target.value);
            });
        }

        // 本地插件搜索
        const localSearchInput = document.getElementById('searchInput');
        if (localSearchInput) {
            let searchTimeout;
            localSearchInput.addEventListener('input', (e) => {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    const statusFilter = document.querySelector('input[name="statusFilter"]:checked')?.value || 'all';
                    this.loadPlugins(1, e.target.value.trim(), statusFilter);
                }, 300); // 300ms延迟，避免频繁请求
            });
        }
    }

    /**
     * 发送API请求
     */
    async request(url, options = {}) {
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.token}`
            }
        };

        if (options.body && !(options.body instanceof FormData)) {
            options.body = JSON.stringify(options.body);
        }

        if (options.body instanceof FormData) {
            delete defaultOptions.headers['Content-Type'];
        }

        const response = await fetch(url, { ...defaultOptions, ...options });
        const data = await response.json();

        if (data.code !== 1) {
            throw new Error(data.msg || '请求失败');
        }

        return data.data;
    }

    /**
     * 加载列表
     */
    async loadPlugins(page = 1, search = '', status = 'all') {
        try {
            this.currentPage = page;
            this.searchKeyword = search;
            this.statusFilter = status;
            this.showLoading('pluginList');

            const params = new URLSearchParams({
                page: page,
                limit: this.pageSize,
                search: search,
                status: status
            });

            const data = await this.request(`${this.baseUrl}/getList?${params}`);
            this.renderPlugins(data.plugins || [], data.pagination);
        } catch (error) {
            this.showError('加载列表失败: ' + error.message);
        }
    }

    /**
     * 渲染列表
     */
    renderPlugins(plugins, pagination = null) {
        // 存储插件数据供其他方法使用
        this.plugins = plugins;

        const container = document.getElementById('pluginList');
        if (!container) return;

        if (plugins.length === 0) {
            const emptyMessage = this.searchKeyword ?
                `<p>没有找到包含 "${this.searchKeyword}" 的内容</p>` :
                `<p>您还没有安装任何应用</p>`;

            container.innerHTML = `
                <div class="text-center py-5">
                    <div class="mb-4" style="font-size: 4rem; opacity: 0.3;">📦</div>
                    <h4 class="text-muted mb-3">暂无内容</h4>
                    <p class="text-muted">${emptyMessage}</p>
                </div>
            `;
            return;
        }

        const html = plugins.map(plugin => `
            <tr>
                <td>
                    <div class="">
                        ${plugin.display_name}
                        <span class="badge bg-info ms-2">v${plugin.version}</span>
                        ${plugin.enabled ?
                            '<span class="badge bg-success ms-1"><i class="fas fa-check-circle"></i> 已启用</span>' :
                            '<span class="badge bg-secondary ms-1"><i class="fas fa-pause-circle"></i> 已停用</span>'
                        }
                    </div>
                    <small class="text-muted">${plugin.plugin_name}</small>
                </td>
                <td>
                    <div class="text-truncate" style="max-width: 500px;" title="${plugin.short_description || '暂无描述'}">
                        ${plugin.short_description || '暂无描述'}
                    </div>
                </td>
                <td>
                    <div class="btn-group btn-group-sm" role="group">
                        ${plugin.enabled ?
                            `<button type="button" class="btn btn-warning btn-sm btn-disable" data-plugin="${plugin.plugin_name}" title="停用插件">
                                <i class="fas fa-pause"></i>
                            </button>` :
                            `<button type="button" class="btn btn-success btn-sm btn-enable" data-plugin="${plugin.plugin_name}" title="启用插件">
                                <i class="fas fa-play"></i>
                            </button>`
                        }
                        ${plugin.enabled ? (plugin.entry ?
                            `<button type="button" class="btn btn-primary btn-sm btn-manage" data-plugin="${plugin.plugin_name}" data-entry="${plugin.entry}" title="插件设置">
                                <i class="fas fa-cog"></i>
                            </button>` :
                            `<button type="button" class="btn btn-info btn-sm btn-config" data-plugin="${plugin.plugin_name}" title="插件配置">
                                <i class="fas fa-wrench"></i>
                            </button>`
                        ) : ''}
                        ${plugin.enabled ?
                            `<button type="button" class="btn btn-secondary btn-sm" disabled title="请先停用插件再删除">
                                <i class="fas fa-trash"></i>
                            </button>` :
                            `<button type="button" class="btn btn-danger btn-sm btn-uninstall" data-plugin="${plugin.plugin_name}" title="删除插件">
                                <i class="fas fa-trash"></i>
                            </button>`
                        }
                    </div>
                </td>
            </tr>
        `).join('');

        let paginationHtml = '';
        if (pagination && pagination.total_pages > 1) {
            paginationHtml = this.renderPagination(pagination);
        }

        container.innerHTML = `
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th width="35%">名称</th>
                        <th width="50%">描述</th>
                        <th width="15%">操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${html}
                </tbody>
            </table>
            ${paginationHtml}
        `;
    }

    /**
     * 渲染分页
     */
    renderPagination(pagination) {
        const { current_page, total_pages, has_prev, has_next } = pagination;

        let paginationHtml = `
            <div class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top">
                <div class="text-muted">
                    第 ${current_page} 页，共 ${total_pages} 页，共 ${pagination.total_count} 个插件
                </div>
                <nav aria-label="插件分页">
                    <ul class="pagination pagination-sm mb-0">
        `;

        // 上一页
        if (has_prev) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="window.pluginManager.loadPlugins(${current_page - 1}, '${this.searchKeyword}', '${this.statusFilter || 'all'}')">上一页</a></li>`;
        } else {
            paginationHtml += `<li class="page-item disabled"><span class="page-link">上一页</span></li>`;
        }

        // 页码
        const startPage = Math.max(1, current_page - 2);
        const endPage = Math.min(total_pages, current_page + 2);

        if (startPage > 1) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="window.pluginManager.loadPlugins(1, '${this.searchKeyword}', '${this.statusFilter || 'all'}')">1</a></li>`;
            if (startPage > 2) {
                paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            const activeClass = i === current_page ? 'active' : '';
            if (i === current_page) {
                paginationHtml += `<li class="page-item ${activeClass}"><span class="page-link">${i}</span></li>`;
            } else {
                paginationHtml += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="window.pluginManager.loadPlugins(${i}, '${this.searchKeyword}', '${this.statusFilter || 'all'}')">${i}</a></li>`;
            }
        }

        if (endPage < total_pages) {
            if (endPage < total_pages - 1) {
                paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
            }
            paginationHtml += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="window.pluginManager.loadPlugins(${total_pages}, '${this.searchKeyword}', '${this.statusFilter || 'all'}')">${total_pages}</a></li>`;
        }

        // 下一页
        if (has_next) {
            paginationHtml += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="window.pluginManager.loadPlugins(${current_page + 1}, '${this.searchKeyword}', '${this.statusFilter || 'all'}')">下一页</a></li>`;
        } else {
            paginationHtml += `<li class="page-item disabled"><span class="page-link">下一页</span></li>`;
        }

        paginationHtml += `
                    </ul>
                </nav>
            </div>
        `;

        return paginationHtml;
    }

    /**
     * 启用插件
     */
    async enablePlugin(pluginName) {
        // 获取插件的中文名
        const plugin = this.plugins.find(p => p.plugin_name === pluginName);
        const displayName = plugin ? plugin.display_name : pluginName;

        layer.confirm(`确定要启用插件 "${displayName}" 吗？`, {
            icon: 3,
            title: '确认启用插件',
            btn: ['确定启用', '取消']
        }, async (index) => {
            layer.close(index);

            const loadingIndex = layer.load(1, {
                shade: [0.3, '#000']
            });

            try {
                await this.request(`${this.baseUrl}/enable`, {
                    method: 'POST',
                    body: { plugin_name: pluginName }
                });

                layer.close(loadingIndex);
                layer.msg('插件启用成功', {
                    icon: 1,
                    time: 1500
                });

                // 只更新插件状态，不重新加载列表
                this.updatePluginStatus(pluginName, true);
            } catch (error) {
                layer.close(loadingIndex);
                layer.msg('插件启用失败: ' + error.message, {
                    icon: 2,
                    time: 3000
                });
            }
        });
    }

    /**
     * 禁用插件
     */
    async disablePlugin(pluginName) {
        // 获取插件的中文名
        const plugin = this.plugins.find(p => p.plugin_name === pluginName);
        const displayName = plugin ? plugin.display_name : pluginName;

        layer.confirm(`确定要禁用插件 "${displayName}" 吗？`, {
            icon: 3,
            title: '确认禁用插件',
            btn: ['确定禁用', '取消']
        }, async (index) => {
            layer.close(index);

            const loadingIndex = layer.load(1, {
                shade: [0.3, '#000']
            });

            try {
                await this.request(`${this.baseUrl}/disable`, {
                    method: 'POST',
                    body: { plugin_name: pluginName }
                });

                layer.close(loadingIndex);
                layer.msg('插件禁用成功', {
                    icon: 1,
                    time: 1500
                });

                // 只更新插件状态，不重新加载列表
                this.updatePluginStatus(pluginName, false);
            } catch (error) {
                layer.close(loadingIndex);
                layer.msg(error.message, {
                    icon: 2,
                    time: 3000
                });
            }
        });
    }

    /**
     * 卸载插件
     */
    async uninstallPlugin(pluginName) {
        // 获取插件的中文名
        const plugin = this.plugins.find(p => p.plugin_name === pluginName);
        const displayName = plugin ? plugin.display_name : pluginName;

        layer.confirm(`确定要卸载插件 "${displayName}" 吗？<br><br><span style="color: #ff4757;">⚠️ 注意：卸载后插件的所有数据将被删除，此操作不可恢复！</span>`, {
            icon: 0,
            title: '确认卸载插件',
            btn: ['确定卸载', '取消'],
            btn1: function(index) {
                layer.close(index);

                const loadingIndex = layer.load(1, {
                    shade: [0.3, '#000']
                });

                window.pluginManager.request(`${window.pluginManager.baseUrl}/uninstall`, {
                    method: 'POST',
                    body: { plugin_name: pluginName }
                }).then(() => {
                    layer.close(loadingIndex);
                    layer.msg('插件卸载成功', {
                        icon: 1,
                        time: 1500
                    });

                    // 移除插件卡片
                    window.pluginManager.removePluginCard(pluginName);
                }).catch(error => {
                    layer.close(loadingIndex);
                    layer.msg(error.message, {
                        icon: 2,
                        time: 3000
                    });
                });
            }
        });
    }

    /**
     * 显示插件配置
     */
    async showConfig(pluginName) {
        // 调用全局函数显示配置弹出层
        if (typeof showConfigModal === 'function') {
            showConfigModal(pluginName);
        } else {
            // 降级到跳转页面
            window.location.href = `/adminapi/plugin/view/config?plugin_name=${pluginName}`;
        }
    }

    /**
     * 打开插件管理页面
     */
    async openPluginManagement(pluginName, entryUrl) {
        // 构建完整URL
        const fullUrl = entryUrl.startsWith('http') ? entryUrl : window.location.origin + entryUrl;

        // 计算合适的弹窗尺寸（响应式）
        const screenWidth = window.screen.width;
        const screenHeight = window.screen.height;
        let width = '1200px';
        let height = '800px';

        // 移动端或小屏幕适配
        if (screenWidth < 1400) {
            width = '95%';
            height = '90%';
        } else if (screenWidth < 1600) {
            width = '90%';
            height = '85%';
        }

        // 使用layer的iframe弹窗
        const layerIndex = layer.open({
            type: 2,
            title: [
                `<i class="layui-icon layui-icon-set" style="margin-right: 8px;"></i>插件管理 - ${pluginName}`,
                'background: white; color: #333; font-weight: 500; border-bottom: 1px solid #e6e6e6;'
            ],
            shadeClose: false, // 点击遮罩不关闭
            shade: 0.4, // 遮罩透明度
            maxmin: true, // 允许最大化最小化
            area: [width, height], // 响应式尺寸
            offset: 'auto', // 自动居中
            content: fullUrl,

            success: function(layero, index) {
                // 弹窗打开成功后的回调

                // 为iframe添加加载完成事件
                const iframe = layero.find('iframe')[0];
                if (iframe) {
                    // 添加加载状态
                    const loadingDiv = $(`
                        <div class="plugin-loading-overlay" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0;
                                    background: rgba(255,255,255,0.9); z-index: 9999; display: flex;
                                    align-items: center; justify-content: center;">
                            <div style="text-align: center;">
                                <div style="width: 40px; height: 40px; border: 3px solid #f3f3f3;
                                            border-top: 3px solid #667eea; border-radius: 50%;
                                            animation: spin 1s linear infinite; margin: 0 auto 10px;"></div>
                                <div style="color: #666; font-size: 14px;">正在加载插件管理页面...</div>
                            </div>
                        </div>
                        <style>
                            @keyframes spin {
                                0% { transform: rotate(0deg); }
                                100% { transform: rotate(360deg); }
                            }
                        </style>
                    `);
                    layero.append(loadingDiv);

                    iframe.onload = function() {
                        // iframe加载完成后移除加载状态
                        layero.find('.plugin-loading-overlay').remove();
                    };

                    // 设置超时，防止加载状态一直显示
                    setTimeout(function() {
                        layero.find('.plugin-loading-overlay').remove();
                    }, 300); // 1秒后强制移除
                }
            },
            end: function() {
                // 弹窗关闭后的回调 - 不需要刷新页面
            }
        });

        // 存储弹窗索引，以便后续操作
        this.currentManagementLayer = layerIndex;
    }

    /**
     * 关闭当前的插件管理弹窗
     */
    closeCurrentManagement() {
        if (this.currentManagementLayer) {
            layer.close(this.currentManagementLayer);
            this.currentManagementLayer = null;
        }
    }

    /**
     * 显示加载状态
     */
    showLoading(containerId) {
        const container = document.getElementById(containerId);
        if (container) {
            container.innerHTML = `
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <div class="mt-2 text-muted">正在加载...</div>
                </div>
            `;
        }
    }

    /**
     * 显示成功消息
     */
    showSuccess(message) {
        layer.msg(message, {
            icon: 1,
            time: 2000
        });
    }

    /**
     * 显示错误消息
     */
    showError(message) {
        layer.msg(message, {
            icon: 2,
            time: 3000
        });
    }

    /**
     * 更新插件状态（不重新加载列表）
     */
    updatePluginStatus(pluginName, enabled) {
        // 首先更新内存中的插件数据
        const plugin = this.plugins.find(p => p.plugin_name === pluginName);
        if (plugin) {
            plugin.enabled = enabled;
        }

        // 查找插件行 - 更精确的选择器
        const pluginRows = document.querySelectorAll('#pluginList tbody tr');

        for (let row of pluginRows) {
            const anyBtn = row.querySelector('[data-plugin]');

            if (anyBtn && anyBtn.dataset.plugin === pluginName) {
                // 更新插件名称列中的状态标签
                const nameCell = row.cells[0];
                if (nameCell) {
                    const statusBadge = nameCell.querySelector('.badge.bg-success, .badge.bg-secondary');
                    if (statusBadge) {
                        statusBadge.className = enabled ? 'badge bg-success ms-1' : 'badge bg-secondary ms-1';
                        statusBadge.innerHTML = enabled ?
                            '<i class="fas fa-check-circle"></i> 已启用' :
                            '<i class="fas fa-pause-circle"></i> 已停用';
                    }
                }

                // 重新渲染整个操作区域
                const actionsCell = row.cells[2]; // 操作列现在是第3列，索引2
                if (actionsCell) {
                    // 获取插件信息
                    const existingConfigBtn = row.querySelector('.btn-config, .btn-manage');
                    const hasEntry = existingConfigBtn && existingConfigBtn.dataset.entry;

                    // 重新生成操作按钮HTML - 直接替换整个按钮组
                    const actionsHtml = `
                        ${enabled ?
                            `<button type="button" class="btn btn-warning btn-sm btn-disable" data-plugin="${pluginName}" title="停用插件">
                                <i class="fas fa-pause"></i>
                            </button>` :
                            `<button type="button" class="btn btn-success btn-sm btn-enable" data-plugin="${pluginName}" title="启用插件">
                                <i class="fas fa-play"></i>
                            </button>`
                        }
                        ${enabled ? (hasEntry ?
                            `<button type="button" class="btn btn-primary btn-sm btn-manage" data-plugin="${pluginName}" data-entry="${existingConfigBtn.dataset.entry}" title="插件设置">
                                <i class="fas fa-cog"></i>
                            </button>` :
                            `<button type="button" class="btn btn-info btn-sm btn-config" data-plugin="${pluginName}" title="插件配置">
                                <i class="fas fa-wrench"></i>
                            </button>`
                        ) : ''}
                        ${enabled ?
                            `<button type="button" class="btn btn-secondary btn-sm" disabled title="请先停用插件再删除">
                                <i class="fas fa-trash"></i>
                            </button>` :
                            `<button type="button" class="btn btn-danger btn-sm btn-uninstall" data-plugin="${pluginName}" title="删除插件">
                                <i class="fas fa-trash"></i>
                            </button>`
                        }
                    `;

                    // 找到按钮组并更新其内容
                    const btnGroup = actionsCell.querySelector('.btn-group');
                    if (btnGroup) {
                        btnGroup.innerHTML = actionsHtml;
                    }
                }
                break;
            }
        }
    }

    /**
     * 移除插件行
     */
    removePluginCard(pluginName) {
        const pluginRows = document.querySelectorAll('.plugin-row');

        for (let row of pluginRows) {
            const configBtn = row.querySelector('.btn-config, .btn-manage');
            if (configBtn && configBtn.dataset.plugin === pluginName) {
                // 添加淡出动画
                row.style.transition = 'opacity 0.3s ease';
                row.style.opacity = '0';

                // 300ms后移除元素
                setTimeout(() => {
                    row.remove();

                    // 检查是否还有插件，如果没有则显示空状态
                    const container = document.getElementById('pluginList');
                    const remainingRows = container.querySelectorAll('.plugin-row');
                    if (remainingRows.length === 0) {
                        container.innerHTML = `
                            <div class="text-center py-5">
                                <div class="mb-4" style="font-size: 4rem; opacity: 0.3;">📦</div>
                                <h4 class="text-muted mb-3">暂无内容</h4>
                                <p class="text-muted">您还没有安装任何插件</p>
                            </div>
                        `;
                    }
                }, 300);
                break;
            }
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.pluginManager = new PluginManager();
});

// 确保PluginManager在全局作用域中可用
window.PluginManager = PluginManager;
